package com.han.news.controller;


import com.han.news.pojo.News;
import com.han.news.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author HanDianWei
 * @since 2021-03-12
 */

@RestController
@RequestMapping("/news")
public class NewsController {
    @Autowired
    private NewsService newsService;
    static String fileLocation = "/gench/pic";  //访问路径
    private Map<String,Object> result = new HashMap<>();

    @GetMapping("/list")
    public List<News> newsList(){
        List<News> newsList = newsService.list(null);
        return newsList;
    }
    @GetMapping("getNewsById")
    public News getNewsById(int n_num){
        News getNewsById = newsService.getById(n_num);
        return getNewsById;
    }

    @PostMapping("/add")
    public Boolean insert(News news){
        boolean saveNews = newsService.save(news);
        return saveNews;
    }



    @PostMapping("/updNews")
    public Boolean updNews(News news){
        boolean updateNews = newsService.updateById(news);
        return updateNews;
    }

    @PostMapping("/delNewsById")
    public Boolean delNews(int n_num){
        boolean delNews = newsService.removeById(n_num);
        return delNews;
    }

    @PostMapping("/upload")
    public String upload(
                         @RequestPart("photo") MultipartFile photo
                         ) throws IOException {
       String msg = "";
        if (!photo.isEmpty()){
           String originalFilename = photo.getOriginalFilename();
           photo.transferTo(new File("D:\\personUpload\\"+originalFilename));
            msg = "D:\\personUpload\\"+originalFilename;
        }
        System.out.println(msg);
       return msg;
    }

    @PostMapping("/uploadImgs")
    public ArrayList upload(@RequestPart("imgs") MultipartFile[] imgs) throws IOException {
        ArrayList msgs = new ArrayList();
        if (imgs.length>0){
            for (MultipartFile img :imgs){
                if (!img.isEmpty()){
                    String originalFilename = img.getOriginalFilename();
                    img.transferTo(new File("D:\\personUpload\\"+originalFilename));
                    String filepath = "D:\\personUpload\\"+originalFilename;
                    msgs.add(filepath);
//                    System.out.println(msgs);
                }
            }

        }
        System.out.println(msgs);
        return msgs;
    }

}

